class Page < ActiveRecord::Base
  acts_as_ferret :fields => [:text]
  
  belongs_to :book
  validates_uniqueness_of :page_number, :scope=>'book_id'
  
  before_create :generate_text_file
  
  def image_file_name
    File.join(PDF_BOOKS_DIR,"%03d.%03d.jpg" % [book.id, page_number])
  end
  
  def sound_file_name
    File.join(PDF_BOOKS_DIR,"%03d.%03d.mp3" % [book.id, page_number])
  end
  
  def text_file_name
    File.join(PDF_BOOKS_DIR,"%03d.%03d.txt" % [book.id, page_number])
  end
  
  def image
    @image ||= Magick::Image.read(image_file_name).first
  end
  
  def sound
    @sound ||= File.read(sound_file_name)
  end
  
  def text
    File.read(text_file_name)
  end
  
  def bookmarks
    book.bookmarks.find_all{|b| b.page_id == id}.sort_by(&:position)
  end
  
  def regions
    book.regions.find_all{|r| r.page_id == id}
  end
  
  def to_param
    page_number.to_s
  end
  
#########################################################################
#########################################################################
###################Sample code to search for pages#######################
#########################################################################
#########################################################################  
#  total_results, members = Page.find_id_by_contents("bla bla")
#results_from_db = Page.find_by_contents("bla bla")
#for member in results_from_db
#  puts member.text
#end

protected
  def generate_text_file
    PdfConvert.pdf_to_text(book.pdf_file_name, page_number, text_file_name)
  end
end
